package org.xzx.shop_api.controller;

import org.xzx.shop_api.constant.ShopConstant;
import org.xzx.shop_api.entity.Cart;
import org.xzx.shop_api.entity.Goods;
import org.xzx.shop_api.service.CartService;
import org.xzx.shop_api.service.GoodsService;
import org.xzx.shop_api.utils.JsonResult;
import org.xzx.shop_api.utils.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 购物车控制器类
 */
@RestController
@RequestMapping("api/cart")
public class CartController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CartService cartService;
    //8.可以把商品加到购物车，且保证不能出现超卖情况，未上架商品不能加到购物车
    @PostMapping("add")
    public JsonResult addCart(@RequestBody Cart cart) {
        //判断商品是否存上架
        int goodsId = cart.getGoodsId();
        Goods goodsInfo = goodsService.getGoodsById(goodsId);
        if (goodsInfo == null || goodsInfo.getStatus() !=1) {
            return JsonResult.failed("该商品不存在，或者已下架");
        }
        //2.判断库存  防止超卖
        int stock = goodsInfo.getStock();//实际库存
        int lockStock = goodsInfo.getLockStock();//锁定库存
        int sellStock = stock - lockStock;
        if (sellStock < 1) {
            return JsonResult.failed("该商品已售完。");
        }
        //判断商品是否重复加入购物车
        Cart result = cartService.getCart(cart.getMemberId(), cart.getGoodsId());
        if (result == null) {
            cart.setCreatedTime(Tool.getCurrentTime());
            cart.setQuantity(1);
            cart.setSelected(1);
            cartService.insertCart(cart);
        } else {
            //修改购买数量
            cartService.updateCart(cart.getMemberId(), cart.getGoodsId(),1);
        }
        return JsonResult.success("ok", null);
    }

    //我的购物车列表
    @GetMapping("list")
    public JsonResult listCart(@RequestParam("member_id") int memberId) {
        List<Cart> cartList = cartService.getCartListByMemberId(memberId);
        for (Cart cart : cartList) {
            Goods goodsInfo = goodsService.getGoodsById(cart.getGoodsId());
            String goodsName = goodsInfo.getGoodsName();
            String goodsImg = goodsInfo.getMainImage();
            cart.setGoodsName(goodsName);
            cart.setGoodsImg(goodsImg);
        }
        return JsonResult.success("ok", cartList);
    }

    //获取购物车合计金额
    @GetMapping("total_amount")
    public JsonResult totalAmount(@RequestParam("member_id") int memberId) {
        List<Cart> results = cartService.getCartListByMemberIdSelected(memberId);

        if (results == null || results.isEmpty()) {
            return JsonResult.success("ok", 0);
        }

        // 校验每个商品是否有效
        for (Cart cart : results) {
            Goods goodsInfo = goodsService.getGoodsById(cart.getGoodsId());
            if (goodsInfo == null || goodsInfo.getStatus() != 1) {
                return JsonResult.failed("购物车中包含无效商品");
            }
        }
        Double totalAmount = cartService.getCartTotalAmount(memberId);
        if (totalAmount == null) {
            totalAmount = 0.0;
        }

        return JsonResult.success("ok", totalAmount);

    }
    //删除购物车商品接口
    @GetMapping("delete")
    public JsonResult delete(@RequestParam(value = "id",defaultValue = "0") int id) {
        if (id <= 0) {
            return JsonResult.failed("删除失败,id不能为空");
        }
        int result = cartService.deleteCartGoodsById(id);
        if (result == 0) {
            return JsonResult.failed("删除失败");
        }
        return JsonResult.success("删除成功", null);
    }

    //单选购物车商品接口
    @GetMapping("selected")
    public JsonResult selected(@RequestParam(value = "id",defaultValue = "0") Long id,
                               @RequestParam(value = "selected",defaultValue = "1") int selected
    ) {
        if (id <= 0) {
            return JsonResult.failed("操作失败,id不能为空");
        }
        int result = cartService.updateSelectedById(id,selected);
        if (result == 0) {
            return JsonResult.failed("操作失败");
        }
        return JsonResult.success("操作成功", null);
    }

    //全选购物车商品接口
    @GetMapping("selected_all")
    public JsonResult selectedAll(@RequestParam(value = "ids",defaultValue = "") String ids,
                               @RequestParam(value = "selected",defaultValue = "1") int selected
    ) {
        if (ids.isEmpty()) {
            return JsonResult.failed("操作失败,id不能为空");
        }
        //ids 1,2,3转为数组
        String idsSql = "(" + ids + ")";
        int result = cartService.batchUpdateSelected(idsSql,selected);
        if (result == 0) {
            return JsonResult.failed("操作失败");
        }
        return JsonResult.success("操作成功", null);
    }

    //改变购物车商品数量
    @PostMapping("update_quantity")
    public JsonResult updateQuantity(@RequestParam(value = "id",defaultValue = "0") int id,
                                     @RequestParam(value = "goods_id",defaultValue = "0") int goodsId,
                                     @RequestParam(value = "quantity",defaultValue = "1") int quantity
                                     ) {
        if (id <= 0) {
            return JsonResult.failed("更新失败,id不能为空");
        }
        //购买数量
        if (quantity <= 0) {
            return JsonResult.failed("更新失败,数量不能为空");
        }
        if (quantity > ShopConstant.QUANTITY_MAX) {
            return JsonResult.failed("更新失败,数量不能超过"+ShopConstant.QUANTITY_MAX);
        }
        //判断库存
        Goods goodsInfo = goodsService.getGoodsById(goodsId);
        if (goodsInfo == null || goodsInfo.getStatus() !=1) {
            return JsonResult.failed("该商品不存在，或者已下架");
        }
        int stock = goodsInfo.getStock();//实际库存
        int lockStock = goodsInfo.getLockStock();//锁定库存
        int sellStock = stock - lockStock;
        if (sellStock < 1) {
            return JsonResult.failed("该商品已售完。");
        }
        int result = cartService.updateCartQuantity(id,quantity);
        if (result == 0) {
            return JsonResult.failed("更新失败");
        }
        return JsonResult.success("更新成功", null);
    }
}
